package com.ccubee.data.transfer.event;

import com.alibaba.otter.canal.protocol.CanalEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;

/**
 * 监听类型上下文
 *
 * @Author ycf
 * @Date 2022/5/22 11:58
 * @Version 1.0
 */
@Slf4j
public class EventTypeContext implements ApplicationContextAware {

    private static final Map<CanalEntry.EventType, IEventType> EVENT_TYPE_MAP = new HashMap<>(16);

    /**
     * 货值执行类型
     *
     * @param eventType 监听类型
     * @return 监听实例
     */
    public static IEventType cmd(CanalEntry.EventType eventType) {
        return EVENT_TYPE_MAP.get(eventType);
    }

    /**
     * 货值执行类型
     *
     * @param isLog     是否输出不存在的监听日志
     * @param eventType 监听类型
     */
    public static void cmd(boolean isLog, CanalEntry.EventType eventType, Cmd cmd) {
        if (!EVENT_TYPE_MAP.containsKey(eventType)) {
            if (isLog) {
                log.warn("eventType not exits,{}", eventType);
            }
            return;
        }
        EVENT_TYPE_MAP.get(eventType).cmd(cmd);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(IEventType.class).forEach((k, v) -> EVENT_TYPE_MAP.put(v.evenType(), v));
    }
}
